package com.ruoyi.cms.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.houbb.opencc4j.util.ZhConverterUtil;
import com.ruoyi.cms.domain.ArticleDraft;
import com.ruoyi.cms.domain.CategoryAccount;
import com.ruoyi.cms.domain.request.ArticleDraftReqDTO;
import com.ruoyi.cms.enums.PlatformEnum;
import com.ruoyi.cms.mapper.ArticleDraftMapper;
import com.ruoyi.cms.mapper.CategoryAccountMapper;
import com.ruoyi.cms.service.IArticleDraftService;
import com.ruoyi.cms.utils.CoreConst;
import com.ruoyi.cms.utils.CrawlerUtil;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 文章草稿Service业务层处理
 *
 * @author ruoyi
 * @date 2020-12-06
 */
@Service
@Slf4j
public class ArticleDraftServiceImpl implements IArticleDraftService {
    @Autowired
    private ArticleDraftMapper articleDraftMapper;
    @Autowired
    private CategoryAccountMapper categoryAccountMapper;
    @Autowired
    private CrawlerUtil crawlerUtil;

    /**
     * 查询文章草稿
     *
     * @param id 文章草稿ID
     * @return 文章草稿
     */
    @Override
    public ArticleDraft selectArticleDraftById(Long id) {
        return articleDraftMapper.selectArticleDraftById(id);
    }

    /**
     * 查询文章草稿列表
     *
     * @param articleDraft 文章草稿
     * @return 文章草稿
     */
    @Override
    public List<ArticleDraft> selectArticleDraftList(ArticleDraft articleDraft) {
        return articleDraftMapper.selectArticleDraftList(articleDraft);
    }

    /**
     * 新增文章草稿
     *
     * @param articleDraft 文章草稿
     * @return 结果
     */
    @Override
    public int insertArticleDraft(ArticleDraft articleDraft) {
        articleDraft.setCreateTime(DateUtils.getNowDate());
        return articleDraftMapper.insertArticleDraft(articleDraft);
    }

    /**
     * 修改文章草稿
     *
     * @param articleDraft 文章草稿
     * @return 结果
     */
    @Override
    public int updateArticleDraft(ArticleDraft articleDraft) {
        articleDraft.setUpdateTime(DateUtils.getNowDate());
        return articleDraftMapper.updateArticleDraft(articleDraft);
    }

    /**
     * 删除文章草稿对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteArticleDraftByIds(String ids) {
        return articleDraftMapper.deleteArticleDraftByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除文章草稿信息
     *
     * @param id 文章草稿ID
     * @return 结果
     */
    @Override
    public int deleteArticleDraftById(Long id) {
        return articleDraftMapper.deleteArticleDraftById(id);
    }

    //以下是根据业务添加的方法

    /**
     * 检查urlHash
     *
     * @param urlHash
     * @return
     */
    public int checkUrlHashUnique(String urlHash) {
        ArticleDraft example = new ArticleDraft();
        example.setUrlHash(urlHash);
        return articleDraftMapper.selectArticleDraftList(example).size();
    }

    /**
     * 批量添加文章草稿记录
     * #2020-5-13 1.过滤未关注账号的文章，并记录日志；
     * 1.1设置分类信息
     * 2.先检验是否已存在（后期将url hash值放redis里）
     * 3.通过url解析文章相关信息（作者、标题、描述、内容）
     * 4.过滤非原创文章
     * 5.过滤含有视频的文章
     * 6.批量插入到pb草稿箱
     *
     * @param reqDTO
     * @return
     */
    @Override
    public int batchAddDrafts(ArticleDraftReqDTO reqDTO) {
        List<ArticleDraft> draftList = new ArrayList<>();
        if (reqDTO.getPlatform() == null || CollectionUtils.isEmpty(reqDTO.getData())) {
            return -1;
        }

        PlatformEnum platform = PlatformEnum.getPlatform(reqDTO.getPlatform());
        if (platform == null) {
            log.error("platform not exist, reqDTO: {}", JSON.toJSONString(reqDTO));
            return -1;
        }

        List<ArticleDraftReqDTO.Data> data = reqDTO.getData();
        switch (platform) {
            /*case WX:
                for (ArticleDraftReqDTO.Data datum : data) {
                    try {
                        //1.过滤未关注公众号，并记录错误日志，后期定时检测该日志
                        //1.1设置分类信息
                        Integer categoryId = -1;
                        String categoryName = "";

                        CategoryAccountExample example = new CategoryAccountExample();
                        example.createCriteria().andWxOriginIdEqualTo(datum.getOriginId())
                                .andPlatformEqualTo(reqDTO.getPlatform()).andDataStateEqualTo(2);
                        List<CategoryAccount> categoryAccounts = categoryAccountMapper.selectByExample(example);
                        if (CollectionUtil.isNotEmpty(categoryAccounts)) {
                            CategoryAccount categoryAccount = categoryAccounts.get(0);
                            if (categoryAccount.getDataState() != 2) {
                                log.error("未关注该公众号，忽略！{}", JSON.toJSONString(datum));
                                continue;
                            }
                            categoryId = categoryAccount.getCateId();
                            categoryName = ZhConverterUtil.toTraditional(categoryAccount.getCateName());
                        } else {
                            log.error("未关注该公众号且账号表中无该账号，忽略！{}", JSON.toJSONString(datum));
                            continue;
                        }

                        //2.检测url是否已存在
                        String urlHash = String.valueOf(datum.getUrl().hashCode());
                        if (checkUrlHashUnique(urlHash) > 0) {
                            log.error("文章已存在，忽略！{}", JSON.toJSONString(datum));
                            continue;
                        }

                        //3.解析文章内容
                        ArticleDraft draft = crawlerUtil.crawlerDraftArticle(datum.getUrl(), PlatformEnum.WX);
                        draft.setPlatform(PlatformEnum.WX.getType());
                        //4.过滤非原创
                        *//*if (draft.getOriginal() == 0) {
                            log.error("非原创文章，忽略！{}", JSON.toJSONString(datum));
                            continue;
                        }*//*
                        //5.过滤音视频文章
                        if (draft.getResult() != null && draft.getResult() == 2) {
                            log.error("文章包含音视频内容，忽略！{}", JSON.toJSONString(datum));
                            continue;
                        }

                        draft.setCategoryId(categoryId);
                        draft.setCategoryName(categoryName);
                        draft.setUrlHash(urlHash);
                        draft.setUrl(datum.getUrl());

                        draftList.add(draft);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("crawlerWxArticle exception, {}", e.getMessage());
                    }
                }
                break;*/
            case TT:
                for (ArticleDraftReqDTO.Data datum : data) {
                    try {
                        //1.过滤未关注公众号，并记录错误日志，后期定时检测该日志
                        //1.1设置分类信息
                        Long categoryId;
                        String categoryName = "";

                        CategoryAccount caCondition = new CategoryAccount();
                        caCondition.setName(datum.getOriginId());
                        caCondition.setPlatform(reqDTO.getPlatform());
                        caCondition.setDataState(2);
                        List<CategoryAccount> categoryAccounts = categoryAccountMapper.selectCategoryAccountList(caCondition);
                        if (!CollectionUtils.isEmpty(categoryAccounts)) {
                            CategoryAccount categoryAccount = categoryAccounts.get(0);
                            /*if (categoryAccount.getDataState() != 2) {
                                log.error("未关注头条号[{}]，忽略！", datum.getOriginId());
                                continue;
                            }*/
                            categoryId = categoryAccount.getCateId();
                            categoryName = ZhConverterUtil.toTraditional(categoryAccount.getCateName());
                        } else {
                            log.error("账号表中无头条号[{}]，忽略！", datum.getOriginId());
                            continue;
                        }

                        String articleId = getArticleIdFromUrl(datum.getUrl());
                        if (StringUtils.isBlank(articleId)) {
                            log.error("头条文章Id解析失败，{}", datum.getUrl());
                            continue;
                        }
                        String toutiaoUrl = String.format(CoreConst.TOUTIAO_ARTICLE_URL, articleId);

                        //2.检测url是否已存在
                        String urlHash = String.valueOf(toutiaoUrl.hashCode());
                        if (checkUrlHashUnique(urlHash) > 0) {
                            log.error("头条文章已存在，忽略！{}", JSON.toJSONString(datum));
                            continue;
                        }

                        //3.解析文章内容
                        ArticleDraft draft = crawlerUtil.crawlerDraftArticle(toutiaoUrl, PlatformEnum.TT);
                        if (StringUtils.isEmpty(draft.getContent())) {
                            log.error("内容为空，忽略！{}", toutiaoUrl);
                            continue;
                        }
                        draft.setPlatform(PlatformEnum.TT.getType());
                        draft.setAuthor(datum.getOriginId());
                        draft.setCategoryId(categoryId);
                        draft.setCategoryName(categoryName);
                        draft.setUrlHash(urlHash);
                        draft.setUrl(toutiaoUrl);

                        draftList.add(draft);
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.err.println("crawlerWxArticle exception," + e.getMessage());
                        log.error("crawlerWxArticle exception, {}", e.getMessage());
                    }
                }
                break;
            default:
                break;
        }

        if (CollectionUtils.isEmpty(draftList)) {
            return -1;
        }

        //6.批量插入到pb草稿箱
        return articleDraftMapper.batchInsert(draftList);
    }

    /**
     * 从url获取articleId
     *
     * @param url toutiao URL
     * @return articleId
     */
    private String getArticleIdFromUrl(String url) {
        String articleId = "";
        if (StringUtils.isNotBlank(url)) {
            if (url.startsWith(CoreConst.TOUTIAO_URL_1)) {
                articleId = url.substring(CoreConst.TOUTIAO_URL_1.length(), url.indexOf("/?app="));
            } else if (url.startsWith(CoreConst.TOUTIAO_URL_2)) {
                articleId = url.substring(CoreConst.TOUTIAO_URL_2.length(), url.indexOf("/?iid="));
            } else {
                return articleId;
            }

            /*if (!isInteger(articleId)) {
                log.error("articleId: {} is error!", articleId);
                return "";
            }*/
        }

        return articleId;
    }
}
